/**
 * 
 */
package jvs.peer.io;

import jvs.peer.util.Log;

import org.apache.commons.pool.KeyedPoolableObjectFactory;

/**
 * @author qiangli
 * 
 */
public class SocketPoolableObjectFactory implements KeyedPoolableObjectFactory {

	private static final Object TAG = "SocketPoolableObjectFactory";
	
	private static int counter = 0;
	

	public Object makeObject(Object key) throws Exception {
		String[] sa = key.toString().split("/");
		
		if (Log.DEBUG) {
			Log.log(TAG, "####### makeObject [" + counter++ + "] " + key);
		}

		PooledSocket so = new PooledSocket(sa[0], Integer.parseInt(sa[1]));

		return so;
	}


	public void destroyObject(Object key, Object obj) throws Exception {
		if (Log.DEBUG) {
			Log.log(TAG, "destroyObject [" + counter + "] " + key);
		}
		
		PooledSocket so = (PooledSocket) obj;
		try {
			so.destroy();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public boolean validateObject(Object key, Object obj) {
		if (Log.DEBUG) {
			Log.log(TAG, "validateObject [" + counter + "] " + key);
		}
		PooledSocket so = (PooledSocket) obj;
		return so.connected;
	}


	public void activateObject(Object key, Object obj) throws Exception {
		if (Log.DEBUG) {
			Log.log(TAG, "activateObject [" + counter + "] " + key);
		}
	}


	public void passivateObject(Object key, Object obj) throws Exception {
		if (Log.DEBUG) {
			Log.log(TAG, "passivateObject [" + counter + "] " + key);
		}
	}

}
